/**
 * Created by Delicate on 2017/5/31.
 */
$(document).ready(function(){
	init();
    monitor();
    service();
});


//重置H5预览页面的样式
function resetPreviewH5Class(id){
//	var ele = $("#preview").contents().find(".advertise").children()
//	$.each(ele, function(i, item){ 
//		if(i%2==0){
//			$(this).attr("class","wayOne");
//			$(this).find("img").attr("class","imgOne")
//		}else{
//			$(this).attr("class","wayTwo");
//			$(this).find("img").attr("class","imgTwo")
//		}
//	});
	$("#preview").contents().find("img_"+id).remove();
	
}

function deleteWrapper(id){
	var delFile = $("#source_"+id).val();
	$("#wrpper_"+id).remove();
	$("#source_"+id).remove();
	$("#preview").contents().find("#img_"+id).remove();
	resetPreviewH5Class(id);
	
	
	//同时删除七牛云上存储的图片
	$.ajax({
		url:contextPath+'/qiniu/deleteQiNiuFile',
		method:"post",
		dataType:"JSON",
		data:{"fileKey":delFile},
		success:function(data){
		}
	})
}


function templateChangeListener(){
	
	$("#taskTemplate").change(function (){
		if($("#taskTemplate").val()!=""){
			$("#preview").attr("src", "/platform/mission?type="+$("#taskTemplate").val());
		}else{
			layer.alert("请选择模板")
		}
	});
}

function initUploader(){
	var srcStr;
    var uploader = WebUploader.create({
        auto: true,
        duplicate:true,
        swf:  contextPath+ '/assets/front/web/script/upload/Uploader.swf',
        server: contextPath+'/qiniu/upload',
        pick: {
            id:'#fileClick'
        },
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
        }
    });
    // 当有文件添加进来的时候
    uploader.on( 'fileQueued', function( file ) {
        var up=$("#uploaded");
        // 创建缩略图
        // thumbnailWidth x thumbnailHeight 为 100 x 100
        uploader.makeThumb( file, function( error, src ) {
            if ( error ) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }
            var file_id ="WU_FILE_"+(up.children().length+1);
            srcStr=src;
            up.append('<div class="u-row-cell-upload-btn" id="wrpper_'+file_id+'"><div id='+file_id+' class="u-row-cell-upload-btn-border" >正在上传</div></div>')
            var delLink = "<div style='text-align:center;'><a href='javascript:;' onclick=deleteWrapper('"+file_id+"') style='color:#c5c2c2'>删除</a></div>";
            var c=$("#"+file_id);
            c.after(delLink);
            c.css('height',"95%");
            var input=$("#hiddenFiles");
            input.append('<input type="hidden" name="source" id="source_'+file_id+'">');
        }, "100", "100" );
    });
    //文件上传成功处理
    uploader.on( 'uploadSuccess', function( file,resp ) {
    	
    	var file_id ="WU_FILE_"+$("#uploaded").children().length;
        var c=$("#"+file_id);
        c.html("");
        c.css('background','url('+resp._raw+') center/contain no-repeat'); 
        var e=$("#source_"+file_id);
        e.val(resp._raw);
        previewH5(resp._raw,file_id);
    });
    //文件上传失败处理
    uploader.on( 'uploadError', function( file ) {
    	layer.alert(file.name+"上传失败！！")
    });
    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
    });

}



function previewH5(url,fileId){
	var html="<img src='"+url+"' id='img_"+fileId+"' width='100%'>";
	$("#preview").contents().find(".advertise").append(html);
	
	var onLineTask_step2 = localStorage.getItem("onLineTask_step2");
	var taskStep2 = JSON.parse(onLineTask_step2);
	taskStep2.imags=$("#preview").contents().find(".advertise").html();
	taskStep2.uploadImags=$("#uploaded").html();
	taskStep2.uploadImagsHidden=$("#hiddenFiles").html();
	localStorage.setItem("onLineTask_step2", JSON.stringify(taskStep2));
}

function checkParam(){
	var extension_type =$("#extension_type").val();
	var h5_type = $("#h5_type").val();
//	var wh_number = $("#wh_number").val();
	if(!extension_type){
		layer.alert("请选择推广类型");
        return false;
	}
	
	if(!h5_type){
		layer.alert("请选择表现形式");
        return false;
	}
	
	//假如指定主播，人数不能超过10个人
//	if(parseInt(wh_number)>10 && extension_type==1){
//        layer.alert("当前推广方式为指定主播模式，只能设置最多10位");
//        return false;
//    }
//	
//	if(parseInt(wh_number)>50 && extension_type==2){
//        layer.alert("当前推广方式为主播认领模式，只能设置最多50位");
//        return false;
//    }
	
	if(h5_type==2&&$("#uploaded").find('div').length < 1){
        layer.alert("请选择要上传的素材");
        return false;
    }
	return true;
}


function saveOnlineTask(){
	var result = checkParam();
	if(result){
		var data = $("#taskForm").serialize();
	    var ajax = new BackendTool({"data":data,"method":"post","url":contextPath+"/platform/task/save"});
	    ajax.successCallBack = successCallBack;
	    ajax.ajaxRequest();
	}
}

function initTaskInfo(){
	$("#next").on("click",function(){
		saveOnlineTask();
	})
	var onLineTask = localStorage.getItem("onLineTask_step1");
	var task = JSON.parse(onLineTask);
	var onLineTask_step2 = localStorage.getItem("onLineTask_step2");
	var taskStep2 = JSON.parse(onLineTask_step2);
	
	if(task && taskStep2){
//		$("#wh_number").val(task.wh_number);
		$("#totalFee").val(task.total_fee);
		$("#task_title").val(task.task_title);
		$("#task_type").val(task.task_type);
		$("#task_price").val(task.task_price);
		$("#task_start_time").val(task.task_start_time);
		$("#task_end_time").val(task.task_end_time);
		$("#task_description").val(task.task_description);
		
		
		$("#extension_type").val(taskStep2.extension_type);
		$("#h5_type").val("2");
		$("#web_url").val(taskStep2.web_url);
		$("#next").unbind();
		if(taskStep2.extension_type=="1"){
			$("#rl").removeClass("u-row-box-check-active");
			$("#zd").addClass("u-row-box-check-active");
			
			//初始化事件
			$("#next").on("click",function(){
        		setFairInfo();
        	})
        	$("#next").html("下一步");
			
		}else{//初始化指定推广方式
			$("#zd").removeClass("u-row-box-check-active");
			$("#rl").addClass("u-row-box-check-active");
			//初始化事件
			$("#next").on("click",function(){
        		saveOnlineTask();
        	})
        	$("#next").html("发布任务");
		}
		
		setTimeout(function(){
			$('#preview').contents().find('.advertise').html(taskStep2.imags);
		},500);
		$("#uploaded").html(taskStep2.uploadImags);
		$("#hiddenFiles").html(taskStep2.uploadImagsHidden);
	}
	
	$("#previous").on("click",function(){
		window.location.href="/platform/task/formNew";
	})
}

function init(){
	var onLineTask = localStorage.getItem("onLineTask_step1");
	var task = JSON.parse(onLineTask);
	var onLineTask_step2 = localStorage.getItem("onLineTask_step2");
	var taskStep2 = JSON.parse(onLineTask_step2);
	if(!taskStep2){
		var tempStep2={
				"extension_type":"2",
				"h5_type":"2",
//				"wh_number":task.wh_number,
				"total_fee":"",
				"web_url":"",
				"imags":"",
				"uploadImags":"",
				"uploadImagsHidden":""
				}
		localStorage.setItem("onLineTask_step2", JSON.stringify(tempStep2));
	}
	//initTaskSort();
	initTaskInfo();
    initUploader();
    //templateChangeListener()
}

function modifyUrl(){
	var step2 = localStorage.getItem("onLineTask_step2");
    var taskStep2 = JSON.parse(step2);
    var url = $("#web_url").val();
    taskStep2.web_url=url;
    localStorage.setItem("onLineTask_step2", JSON.stringify(taskStep2));
}

function modifyWhNum(){
	var step1 = localStorage.getItem("onLineTask_step1");
    var taskStep1 = JSON.parse(step1);
	var step2 = localStorage.getItem("onLineTask_step2");
    var taskStep2 = JSON.parse(step2);
    var wh_num = $("#wh_number").val();
    taskStep2.wh_number=wh_num;
    taskStep1.wh_number=wh_num;
    localStorage.setItem("onLineTask_step2", JSON.stringify(taskStep2));
    localStorage.setItem("onLineTask_step1", JSON.stringify(taskStep1));
}

function monitor(){
	
	$("#tgfs .u-row-box-check").on("click",function(){
        $("#tgfs .u-row-box-check-active").removeClass("u-row-box-check-active");
        $(this).addClass("u-row-box-check-active");
        var code = $(this).attr("code");
        $("#extension_type").val(code);
        $("#next").unbind();
        var step2 = localStorage.getItem("onLineTask_step2");
        var taskStep2 = JSON.parse(step2);
        if(code=="2"){
        	$("#wh_number").attr("readonly",false);
        	taskStep2.extension_type="2"
        	$("#next").on("click",function(){
        		saveOnlineTask();
        	})
        	$("#next").html("发布任务");
        }else{
        	taskStep2.extension_type="1"
        	$("#wh_number").attr("readonly",false);
        	$("#next").on("click",function(){
        		setFairInfo();
        	})
        	$("#next").html("下一步");
        }
		localStorage.setItem("onLineTask_step2", JSON.stringify(taskStep2));
    });
	
    $("#bxxs .u-row-box-check").on("click",function(){
        $("#bxxs .u-row-box-check-active").removeClass("u-row-box-check-active");
        $(this).addClass("u-row-box-check-active");
        $("#h5_type").val($(this).attr("code"));
        if($(this).attr('code') === '1'){
            $("#pic_panel").hide();
        }else{
            $("#pic_panel").show();
        }
    });
    
}
function service(){

}

var successCallBack=function(data){
	if(data.result){
		var id = data.data;
		localStorage.removeItem("onLineTask_step1");
		localStorage.removeItem("onLineTask_step2");
		window.location.href= contextPath+'/platform/task/dispatcher?id='+id;
    }else{
        layer.alert(data.msg)
    }
}

function setFairInfo(){
	
	var result = checkParam();
	if(result){
		var extension_type =$("#extension_type").val();
		var h5_type = $("#h5_type").val();
//		var wh_number = $("#wh_number").val();
		var totalFee = $("#totalFee").val();
		var web_url = $("#web_url").val();
		var imags = $("#preview").contents().find(".advertise").html();
		var uploadImags = $("#uploaded").html();
		var hiddenFiles = $("#hiddenFiles").html();
		var taskCache = localStorage.getItem("onLineTask_step2");
		taskCache= JSON.parse(taskCache);
		taskCache.extension_type = extension_type;
		taskCache.h5_type = h5_type;
		taskCache.web_url = web_url;
		taskCache.imags = imags;
		taskCache.uploadImags = uploadImags;
		taskCache.uploadImagsHidden = hiddenFiles;
		localStorage.setItem("onLineTask_step2", JSON.stringify(taskCache));
		var data = $("#taskForm").serialize();
	    var ajax = new BackendTool({"data":data,"method":"post","url":contextPath+"/platform/task/save"});
	    ajax.successCallBack = successCallBack;
	    ajax.ajaxRequest();
	}
	
}





